#include <iostream>
#include <cmath>
#include <vector>
#include <functional>
#include <fstream>
#include "newton_interpolation.hpp"

double f(double x){
	return (1/(1 + x*x));
}


void generateData(const std::string& filename, std::function<double(double)> f) {
    int N = 1000;
    std::vector<double> x, y;  
    //x.clear();  
    //y.clear();  
    std::ofstream datafile(filename);  
    if (datafile.is_open()) {  
        for (int i = 0; i < N; i++) {  
            x.push_back(-5. + i * 10. / N);  
            y.push_back(f(x[i]));  
            datafile << x[i] << " " << y[i] << std::endl;  
        }  
        datafile.close();  
    } else {  
        std::cerr << "Unable to open file";  
    }  
}

void NewtonData(const std::string& filename, NewtonInterpolation f) {
    int N = 1000;
    std::vector<double> x, y;  
    //x.clear();  
    //y.clear();  
    std::ofstream datafile(filename);  
    if (datafile.is_open()) {  
        for (int i = 0; i < N; i++) {  
            x.push_back(-5. + i * 10. / N);  
            y.push_back(f.interpolate(x[i]));  
            datafile << x[i] << " " << y[i] << std::endl;  
        }  
        datafile.close();  
    } else {  
        std::cerr << "Unable to open file";  
    }  
}  


 int main(){
   std::vector<double> x;
   std::vector<double> y;
   std::vector<NewtonInterpolation> ip_Functions(4);
   std::vector<std::string> filename = {"data_2.txt","data_4.txt","data_6.txt","data_8.txt"};
   
   for (int j = 0; j < 4; j++){
     x.clear();
     y.clear();
	for (int i = 0; i <= 2*j+2; i++){
	  x.push_back(-5. + 10.*i/(2*j+2));
	  y.push_back(f(x[i]));
	} 
	NewtonInterpolation f = NewtonInterpolation(x,y);
	NewtonData(filename[j],f);
	//ip_Functions[j] = NewtonInterpolation(x,y);
   }
	generateData("data.txt",f);
	/*
        NewtonData("data_2.txt",ip_Functions[0]);
	NewtonData("data_4.txt",ip_Functions[1]);
	NewtonData("data_6.txt",ip_Functions[2]);	
	NewtonData("data_8.txt",ip_Functions[3]);
	*/

    return 0;  
}  

//plot "data.txt","data_2.txt","data_4.txt","data_6.txt","data_8.txt"
